<template>
  <div class="phone-box">

    <div id="PhoneBox" :style="collapsed?'width: 229px':'width: 80px'">
      <a-card :class="light_dark_class">
        <div class="g-no-wrap" >
          <span >连接状态：</span>
          <a-badge v-if="collapsed"  :status="connect.status" :text="connect.text"/>
          <a-badge v-else style="margin-left: -5px;" :status="connect.status" />
        </div>
        <div class="g-no-wrap" >
          <span >设备状态：</span>
          <a-badge v-if="collapsed" :status="equipment.status" :text="equipment.text" />
          <a-badge v-else style="margin-left: -5px;" :status="equipment.status"  />
        </div>
        <!--        <p class="p-class">设备名称：{{currDeviceName}}</p>-->
        <!--        <p class="p-class">本地音量：{{localVolume}}</p>-->
        <!--        <p class="p-class">对方音量：{{phoneVolume}}</p>-->
        <p class="p-class" v-if="collapsed" >通话状态：{{txtTalkState}}  </p>
        <p class="p-class " v-else >状态：<span> {{txtTalkState}}</span></p>
        <!--        <p class="p-class">通话号码：{{txtTalkNumber}}</p>-->
        <!--        <p class="p-class">通话类型：{{txtTalkType}}</p>-->
        <!--        <p class="p-class">ccid：{{ccidContent}}</p>-->
        <!--      <p>ccid服务内容：{{serviceContent}}</p>-->
        <!--      <p>型号名称：{{txtModelName}}</p>-->
        <!--      <p>软件版本：{{txtSwVersion}}</p>-->
        <!--      <p>固件版本：{{txtHwVersion}}</p>-->
        <!--        <a-card >-->
        <!--          <a-card-grid :style="sims[0].sim0cur==='(当前正在使用)'?'background-color: #3399ff':'background-color: none'" class="g-flex g-y-center" >-->
        <!--            <div class="card-index">2</div><span style="font-size: 14px;">{{sims[0].sim0state}}</span>-->
        <!--          </a-card-grid>-->
        <!--          <a-card-grid :style="sims[1].sim1cur==='(当前正在使用)'?'background-color: #3399ff':'background-color:none'" class="g-flex g-y-center">-->
        <!--            <div class="card-index">2</div><span style="font-size: 14px;">{{sims[1].sim1state}}</span>-->
        <!--          </a-card-grid>-->
        <!--          <a-card-grid :style="sims[2].sim2cur==='(当前正在使用)'?'background-color: #3399ff':'background-color: none'" class="g-flex g-y-center">-->
        <!--            <div class="card-index">3</div><span style="font-size: 14px;">{{sims[2].sim2state}}</span>-->
        <!--          </a-card-grid>-->
        <!--          <a-card-grid :style="sims[3].sim3cur==='(当前正在使用)'?'background-color: #3399ff':'background-color: none'" class="g-flex g-y-center">-->
        <!--            <div class="card-index">4</div><span style="font-size: 14px;">{{sims[3].sim3state}}</span>-->
        <!--          </a-card-grid>-->
        <!--          <a-card-grid :style="sims[4].sim4cur==='(当前正在使用)'?'background-color: #3399ff':'background-color: none'" class="g-flex g-y-center" >-->
        <!--            <div class="card-index">5</div><span style="font-size: 14px;">{{sims[4].sim4state}}</span>-->
        <!--          </a-card-grid>-->
        <!--        </a-card>-->
        <!--        <div class="g-flex g-y-center g-x-between">-->
        <!--          <a-input-number v-model="inputNumber" style="width: 120px;margin-top: 8px;" />-->
        <!--          <a-button type="primary" @click="OnDial(inputNumber,true)"style="margin-top: 7px;padding: 5px">呼叫</a-button>-->
        <!--          <a-button type="danger" @click="closeTel" style="margin-top: 7px;padding: 5px">挂断</a-button>-->
        <!--        </div>-->

      </a-card>
      <div>
        <a-button v-if="collapsed" @click="OnInitDevice" type="primary" style="padding: 5px;">初始化设备</a-button>
        <a-button v-else @click="OnInitDevice" type="primary" style="padding: 0 4px;font-size: 12px;margin-left: 5px; ">初始化设备</a-button>
      </div>
    </div>
  </div>

</template>

<script>
import {getUserPhoneBox} from '@/api/components/callPhone'
import {mapState} from 'vuex'
import Bus from '@/utils/bus'

export default {
  name: "PhoneBox",
  data() {
    return {
      equipment: {//设备连接
        status: "error",
        text: "断开"
      },
      connect: {//客户端连接
        status: "error",
        text: "断开"
      },
      path: "ws://127.0.0.1:8555/api",
      socket: "",
      currDeviceName: "",//当前设备名称
      inputNumber: "",//输入手机号码
      localVolume: "",//本地音量
      phoneVolume: "",//对方音量
      localaudio: "",//本地音量【设置】
      phoneaudio: "",//对方电话音量【设置】
      txtTalkNumber: '',//通话号码
      txtTalkState: "",//通话状态
      txtTalkType: "",//通话类型
      ccidContent: "", //ccid
      serviceContent: "", //ccid服务内容
      //设备版本信息
      txtModelName: "",//型号名称
      txtSwVersion: "",//软件版本
      txtHwVersion: "",//固件版本
      sims: [
        {sim0state: "", sim0cur: ""},//卡1状态/ /卡1状态
        {sim1state: "", sim1cur: ""},//卡1状态/ /卡1状态
        {sim2state: "", sim2cur: ""},//卡1状态//卡1状态
        {sim3state: "", sim3cur: ""},//卡1状态//卡1状态
        {sim4state: "", sim4cur: ""},//卡1状态//卡1状态
        {sim5state: "", sim5cur: ""}//卡1状态//卡1状态
      ],

    }
  },
  mounted() {
    // 初始化
    this.init()

    // Bus.$off('OnAnswer')
    // Bus.$off('OnDial')
    // Bus.$off('OnCBSwitchNext')
    // Bus.$off('OnHangup')
    Bus.$on('OnAnswer', flag => {
      this.OnAnswer()
    })
    Bus.$on('OnDial', obj => {
      const contactContent = obj.contactContent
      const type = obj.type
      this.OnDial(contactContent, type)
    })
    Bus.$on('OnCBSwitchNext', () => {
      this.OnCBSwitchNext()
    })
    Bus.$on('OnHangup', () => {
      this.OnHangup()
    })

  },
  computed: {
    ...mapState({
      collapsed: state => state.app.sidebar,
      themeIsLight:  state => state.app.theme=='light'?true:false
    }),
    light_dark_class(){
      return{
        'light-class':this.themeIsLight,
        'dark-class':!this.themeIsLight
      }
    }
  },
  methods: {
    init() {
      if (typeof (WebSocket) === "undefined") {
        alert("您的浏览器不支持socket")
      } else {
        // 实例化socket
        this.socket = new WebSocket(this.path)
        // 监听socket连接
        this.socket.onopen = this.open
        // 监听socket错误信息
        this.socket.onerror = this.error
        // 监听socket消息
        this.socket.onmessage = this.getMessage
      }
    },
    closeTel() {
      this.OnHangup()
    },
    open() {
      //setTimeout(this.socket.send('{"command":"closeoldws"}'),1000)//关闭旧链接 防止网页多开 需要时使用
      //this.socket.send('{"command":"closeoldws"}')
      setInterval(this.HeartBeatCheck, 60000)//设置心跳 1分钟间隔
      this.connect = {
        status: "success",
        text: "在线"
      }
      this.$store.commit('phoneBox/setConnect', true)
      this.OnOpenDevice()
      console.log("socket已启动")
    },
    error() {
      this.$store.commit('phoneBox/setEquipment', false)
      // console.log('设备连接状态', this.$store.state.phoneBox)
    },
    //设备状态
    getMessage(msg) {
      // console.log(msg.data)
      let msgData = JSON.parse(msg.data)//回调数据
      let type = msgData.type// 回调数据类型
      if (type === "CommandResponse") {//请求返回
        let state = msgData.data.state
        let command = msgData.data.invoke_command
        if (state === true) {
          let dynamicdata = msgData.dynamicdata
          if (command === 'GetConnectedState_Multi') {//设备列表
            let deviceList = dynamicdata.devicelist
            if (deviceList === "") {
              this.$store.commit('phoneBox/setEquipment', false)
              this.equipment = {

                status: "error",
                text: "断开"
              }
            } else {
              this.currDeviceName = deviceList.split(',')[0]
              this.equipment = {
                status: "success",
                text: "在线"
              }
              this.$store.commit('phoneBox/setEquipment', true)
              this.OnGetTalkState()
              this.OnGetVolume()
              this.OnGetCCID()
              this.OnGetCBCurrState()
              this.OnGetCBCurrSIM()
              this.OnGetDeviceProductInfo()
              this.OnGetConfig()
              this.OnGetErrorUploadCount()
            }
          }
          if (command === "GetDeviceAudio_Multi") {//获取音量
            this.localVolume = dynamicdata.localaudio
            this.phoneVolume = dynamicdata.phoneaudio
            //$("#localVolumeNum").text($("#localVolume").val())
            //$("#phoneVolumeNum").text($("#phoneVolume").val())
          }
          if (command === "GetTalkState_Multi") {//获取通话状态
            let talkModel = dynamicdata
            let talkNumber = talkModel.number
            let talkType = talkModel.type === '' ? '' : talkModel.type === 'out' ? '呼出' : '呼入'
            let talkState
            switch (talkModel.realtimestate) {
              case 'outgoing':
                talkState = '呼出中'
                break
              case 'ringback':
                talkState = '振铃中'
                break
              case 'incoming':
                talkState = '呼入中'
                break
              case 'outconnected':
                talkState = '呼出接通'
                break
              case 'inconnected':
                talkState = '呼入接通'
                break
              case 'hangup':
                talkState = '挂断'
                break
              case 'idle':
                talkState = '空闲'
                break
              default:
                break
            }
            this.txtTalkNumber = talkNumber
            this.txtTalkState = talkState
            this.txtTalkType = talkType
            this.$store.commit('phoneBox/setCallState', talkState)
          }
          if (command === "GetCCID_Multi") {//获取CCID
            this.ccidContent = dynamicdata.ccid
            this.ccidContent && window.localStorage.setItem('ccid', this.ccidContent)
            this.serviceContent = dynamicdata.service
          }
          if (command === "GetCBCurrState_Multi") {//插卡状态
            let stateList = dynamicdata.split(',')
            for (let i = 0; i < 5; i++) {
              let state = stateList[i] == 0 ? '空' : '已插入'
              this.sims[i][`sim${i}state`] = state
            }
          }
          if (command === "GetCBCurrSim_Multi") {//获取当前SIM卡索引
            for (let i = 0; i < 5; i++) {
              this.sims[i][`sim${i}cur`] = ''
            }
            let currSIMIndex = dynamicdata.simid
            this.sims[currSIMIndex][`sim${currSIMIndex}cur`] = '(当前正在使用)'
          }
          if (command === "GetDeviceInfo_Multi") {//获取设备版本信息
            this.txtModelName = dynamicdata.model_name
            this.txtSwVersion = dynamicdata.sw_version
            this.txtHwVersion = dynamicdata.hw_version
          }
        }
      }
      if (type === 'DeviceConnectedState') {//设备连接状态上报
        this.OnGetConnectedState()
      }
      //实时通讯状态
      if (type === 'RealTimeState') {//实时状态
        let talkModel = msgData.dynamicdata
        let talkNumber = talkModel.number
        let talkType = talkModel.type === '' ? '' : talkModel.type === 'out' ? '呼出' : '呼入'
        let talkState
        switch (talkModel.realtimestate) {
          case 'outgoing':
            talkState = '呼出中'
            break
          case 'ringback':
            talkState = '振铃中'
            break
          case 'incoming':
            talkState = '呼入中'
            getUserPhoneBox(talkNumber).then(res => {
              console.log('来电结果为', res)
              Bus.$emit('showPhone')
              this.$store.commit('phoneBox/setCall', 'incoming')
              this.$store.commit('phoneBox/setCallVisible', true)
              this.$store.commit('phoneBox/setCallValue', res.data)
            })

            break
          case 'outconnected':
            talkState = '呼出接通'
            break
          case 'inconnected':
            talkState = '呼入接通'
            break
          case 'hangup':
            talkState = '挂断'
            Bus.$emit('hangup')
            break
          case 'idle':
            talkState = '空闲'
            break
          default:
            break
        }
        this.txtTalkNumber = talkNumber
        this.txtTalkState = talkState
        this.txtTalkType = talkType
        this.$store.commit('phoneBox/setCallState', talkState)
      }

    },
    send(params) {
      this.socket.send(params)
    }
    ,
    close() {
      console.log("socket已经关闭")
    }
    ,
    //电话盒子更新
    HeartBeatCheck() {//心跳检测
      this.send('HeartBeatData')
    }
    ,
    OnOpenDevice() {//打开连接
      this.send('{"command":"OpenDevice_Multi"}')
      setTimeout(this.OnGetConnectedState, 3000)
    }
    ,
    OnGetConnectedState() {//获取设备连接列表
      this.send('{"command":"GetConnectedState_Multi"}')
    }
    ,
    //初始化设备
    OnInitDevice() {
      this.connect = this.equipment = {
        status: "error",
        text: "断开"
      }
      this.currDeviceName = ""
      this.init()
    },
    OnDial(number, isSearch = false) {//拨号
      if (number !== "") {
        // Bus.$emit('showPhone',number)
        this.$store.commit('phoneBox/setCall', 'select')
        this.$store.commit('phoneBox/setCallVisible', true)
        this.send('{"command":"Dial_Multi","arguments":{"phone":"' + number + '","devicename":"' + this.currDeviceName + '"}}')
      }
    },
    OnHangup() {//挂断
      this.send('{"command":"HangUp_Multi","arguments":{"devicename":"' + this.currDeviceName + '"}}')
      // this.$emit('hiddenDom')
    }
    ,
    OnAnswer() {//接听
      this.send('{"command":"Answer_Multi","arguments":{"devicename":"' + this.currDeviceName + '"}}')
    },
    OnGetTalkState() {//获取当前通话状态
      this.send('{"command":"GetTalkState_Multi","arguments":{"devicename":"' + this.currDeviceName + '"}}')
    },
    OnGetSign() {//获取信号值
      this.send('{"command":"GetSignalLevel_Multi","arguments":{"devicename":"' + this.currDeviceName + '"}}')
    },

    OnGetCCID()//获取CCID及运营商信息
    {
      this.send('{"command":"GetCCID_Multi","arguments":{"devicename":"' + this.currDeviceName + '"}}')
    },
    OnGetVolume() {//读取音量
      this.send('{"command":"GetDeviceAudio_Multi","arguments":{"devicename":"' + this.currDeviceName + '"}}')
    },
    OnSetVolume() {//设置音量
      this.send('{"command":"SetDeviceAudio_Multi","arguments":{"devicename":"' + this.currDeviceName + '","localaudio":"' + this.localaudio + '","phoneaudio":"' + this.phoneaudio + '"}}')
    },
    OnGetCBCurrState() {//获取卡槽状态
      this.send('{"command":"GetCBCurrState_Multi","arguments":{"devicename":"' + this.currDeviceName + '"}}')
    },
    OnGetDeviceProductInfo() {//获取设备型号信息
      this.send('{"command":"GetDeviceInfo_Multi","arguments":{"devicename":"' + this.currDeviceName + '"}}')
    },
    OnGetConfig() {//读取配置
      this.send('{"command":"GetConfig"}')

    },
    OnGetCBCurrSIM() {//获取当前使用SIM卡索引 0-4
      this.send('{"command":"GetCBCurrSim_Multi","arguments":{"devicename":"' + this.currDeviceName + '"}}')
    },

    OnCBSwitchNext() {//顺序换卡
      this.send('{"command":"CBSwitchNext_Multi","arguments":{"devicename":"' + this.currDeviceName + '"}}')
    },

    OnCBSwitch() {//指定索引换卡
      var simIndex = $("#simIndex").val()
      this.send('{"command":"CBSwitch_Multi","arguments":{"devicename":"' + this.currDeviceName + '","content":"' + simIndex + '"}}')
    },
    OnStartRecord()//开始录音
    {
      this.send('{"command":"StartRecord_Multi","arguments":{"devicename":"' + this.currDeviceName + '"}}')
    },
    OnStopRecord()//停止录音
    {
      this.send('{"command":"StopRecord_Multi","arguments":{"devicename":"' + this.currDeviceName + '"}}')
    },
    OnTalkPlayAudio()//通话中开始播放默认音频
    {
      this.send('{"command":"closeheadsettochannel_Multi","arguments":{"devicename":"' + this.currDeviceName + '"}}')
      this.send('{"command":"PlayStartRecord_Multi","arguments":{"devicename":"' + this.currDeviceName + '","content":"ringmusic\\TestAudio.wav"}}')
    },
    OnTalkStopAudio()//通话中结束播放默认音频
    {
      this.send('{"command":"openheadsettochannel_Multi","arguments":{"devicename":"' + this.currDeviceName + '"}}')
      this.send('{"command":"PlayStopRecord_Multi","arguments":{"devicename":"' + this.currDeviceName + '"}}')

    },
    OnUploadByURL()//上传录音文件到指定url
    {
      var url = $("#uploadPostURL").val()
      var fileName = $("#recordPath").val()
      if (fileName == "") {
        alert("请先手动录音")
        return
      }
      if (url == "") {
        alert("请输入正确URL")
        return
      }
      this.send('{"command":"UploadFile", "arguments":{"url":"' + url + '", "file":"' + fileName + '"}}')

    },
    OnGetErrorUploadCount() {//获取推送失败记录
      this.send('{"command":"GetUpdloadErrorLog"}')
      this.send('{"command":"GetUploadErrorRecord"}')
    }
  }
  ,
  destroyed() {
    // 销毁监听
    this.socket.onclose = this.close
  }
}
</script>

<style lang="less" scoped>
#PhoneBox {
  //width: 12%;
  position: fixed;
  bottom: 20px;
  font-size: 12px;
  color: #cccccc;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/deep/ .ant-card {
  background: none;
  color: #ffffff;
}

/deep/ .ant-card-body {
  padding: 10px 2px 5px 5px;
}

/deep/ .ant-card-head {
  padding: 6px;
}

/deep/ .ant-card-head-title {
  padding: 0px 0 !important;
}

/deep/ .ant-card-grid {
  padding: 10px 5px;
}

/deep/ .ant-drawer-content-wrapper {
  height: 498px !important;
  bottom: 0 !important;
}

/deep/ .ant-drawer .ant-drawer-content {
  height: 498px !important;
  bottom: 0;
}

.p-class {
  line-height: 27px;
  margin-bottom: 0;
  white-space: nowrap;
}

.card-index {
  border-radius: 50%;
  width: 15px;
  height: 15px;
  line-height: 13px;
  text-align: center;
  border: 1px solid #ffffff;
  font-size: 12px;
  margin-right: 6px;
}

/deep/ .ant-card-bordered {
  border: none;
}

.light-class{
  color: rgba(0, 0, 0, 0.65);
  /deep/ .ant-badge-status-text{
    color: rgba(0, 0, 0, 0.65);
  }
}
.dark-class{
  color: rgba(255, 255, 255, 0.65);
   /deep/ .ant-badge-status-text{
     color: rgba(255, 255, 255, 0.65);
   }
}
</style>